package com.easthome.controller;

import com.easthome.constant.MessageConstant;
import com.easthome.entity.PageResult;
import com.easthome.entity.QueryPageBean;
import com.easthome.pojo.SetMeal;
import com.easthome.result.Result;
import com.easthome.service.SetMealService;
import com.easthome.util.FileUploadUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setMeal")
public class SetMealController {
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private  FileUploadUtil fileUploadUtil;
    /**
     * 分页查询
     */
    @PostMapping("/querySetMealPage")
    public Result querySetMealPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = setMealService.querySetMealPage(queryPageBean);
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,pageResult);
    }

    /**
     * 添加套餐
     */
    @PostMapping("/addSetMeal")
    public Result addSetMeal( Integer[] checkGroupIds, @RequestBody SetMeal setMeal){
        setMealService.addSetMeal(checkGroupIds,setMeal);
        return  new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }
    /**
     * 接收套餐设置功能的文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile) throws IOException {
        System.out.println("imgFile = " + imgFile);
        //获取文件名
        String originalFilename = imgFile.getOriginalFilename();
        //获取文件后缀名
        String extension = FilenameUtils.getExtension(originalFilename);
        //重新定义文件名 公司域名+毫秒值+uuid随机值
        String filename = "zut"+System.currentTimeMillis()
                + UUID.randomUUID().toString().replace("-", "")+"."+extension;
        System.out.println("filename = " + filename);

        //通过springmvc的上传接口
        fileUploadUtil.fileupload(imgFile.getInputStream(), filename);
        return new Result(true, MessageConstant.UPLOAD_SUCCESS,
                "http://localhost:9000/picture/"+filename);
    }
}
